/**
 * Created by Administrator on 2019/1/28.
 */
const Service = require('egg').Service;
const fs = require('fs');
const path = require('path');
const config = require('../utils/config')
const dir = config.fileDir + '/user'
const xlsx = require('node-xlsx');
const theadMap = require('../utils/config').thead;
const util = require('../utils/index');

class loginService extends Service {
  async getAll() {
    const s1 = this.getS1(); // sheet1的数据所有人所有数据集合
    const s2 = this.getS2(s1); // 所有人，总计集合
    const url = createExcel(s1, s2); // 本地创建表格并返回url
    return url;
  }

  getS1() {
    const fileList = []; // {path, filename}
    const excels = [];
    let thead = [];
    const tbody = [];
    readFileList(dir, fileList);
    // readFileList('X:/Users/Eve/Desktop/qqqqqqqqqqqqqqqqqqq', fileList);
    if (fileList.length) {
      fileList.forEach(file => {
        excels.push(xlsx.parse(file.path, { cellDates: true }));
      });

      excels.forEach(excel => {

        if (!thead.length) {
          thead = [ ...excel[0].data[0] ];
        }
        excel[0].data.shift(); // 去除表头
        excel[0].data.forEach(item => {
          if (!item.length) return;

          // 时间格式化
          if (typeof item[theadMap.startTime] === 'object') {
            item[theadMap.startTime] = util.parseTime(item[theadMap.startTime]).slice(11, 16);
          }
          if (typeof item[theadMap.endTime] === 'object') {
            item[theadMap.endTime] = util.parseTime(item[theadMap.endTime]).slice(11, 16);
          }

          tbody.push(item);
        });
      });
    }
    const res = [ thead, ...tbody ];

    return res;


  }

  getS2(s1) {
    const map = {}; //
    if (s1 && s1.length) {
      // 计算所有人的综合
      s1.forEach((item, index) => {
        if (index > 0) {
          let name = item[theadMap.name],
            foodMoney = 0,
            carMoney = 0;
          if (item[theadMap.food] != null && Number(item[theadMap.food]) > 0) foodMoney = Number(item[theadMap.food]);
          if (item[theadMap.car] != null && Number(item[theadMap.car]) > 0) carMoney = Number(item[theadMap.car]);

          if (!map[name]) {
            map[name] = { foodMoney: 0, carMoney: 0 };
          }

          map[name].foodMoney += foodMoney;
          map[name].carMoney += carMoney;
        }
      });

      const res = [
        [ '姓名', '餐费', '交通费', '金额小计', '备注' ],
      ];
      // 生成表格数据
      for (const key in map) {
        const user = map[key];
        res.push([ key, user.foodMoney, user.carMoney, user.foodMoney + user.carMoney ]);
      }
      calcSum(res);
      return res;
    }
  }
}

/**
 * 计算表格最下面的合计
 * @param list
 */
function calcSum(list) {
  let foodSum = 0,
    carSum = 0;
  try {
    if (list && list.length) {
      list.forEach((item, index) => {
        if (index > 0) {
          foodSum += Number(item[1]);
          carSum += Number(item[2]);
        }
      });

      list.push([ '合计', foodSum, carSum, foodSum + carSum ]);
    }
  } catch (e) {

  }

}

function createExcel(s1, s2) {
  const s1Opts = { '!cols': [{ wch: 20 }, { wch: 10 }, { wch: 8 }, { wch: 20 }, { wch: 14 }, { wch: 14 }, { wch: 10 }, { wch: 10 }, { wch: 11 }, { wch: 22 }] };
  const s2Opts = { '!cols': [{ wch: 9 }, { wch: 10 }, { wch: 10 }, { wch: 10 }, { wch: 20 }] };

  const buffer = xlsx.build([{ name: 'sheet1', data: s1, options: s1Opts }, { name: 'sheet2', data: s2, options: s2Opts }]); // Returns a buffer

  const fileName = new Date().getMonth() + 1 + '-monthTotal.xlsx'; // 月度汇总表
  const filePath = config.fileDir + '/' + fileName;
  fs.writeFileSync(filePath, buffer, 'binary');
  return config.downPath + fileName
}

function readFileList(path, filesList) {
  const files = fs.readdirSync(path);
  try {
    files.forEach((file, index) => {
      const stat = fs.statSync(path + '/' + file);
      if (stat.isDirectory()) {
        // 递归读取文件
        readFileList(path + '/' + file, filesList);
      } else {
        if (file.indexOf('.xlsx') > -1) {
          const obj = {};// 定义一个对象存放文件的路径和名字
          obj.path = path + '/' + file;// 路径
          obj.filename = file;// 名字
          filesList.push(obj);
        }
      }
    });
  } catch (e) {

  }
}

module.exports = loginService;
